using System;
using System.Net;
using System.Text;
using System.Web;

namespace VariationSettings
{
    /// <summary>
    /// This class contains all functionality to call the create hierachies function
    /// in Sharepoint, because of the internal scope of the variationsettings in 
    /// Microsoft.Sharepoint.Publishing a webclient is used
    /// </summary>
    /// <remarks>Expirimental</remarks>
    internal static class HttpBee
    {
        internal static void CreateHierachies(ProgramInputs input)
        {
            using (WebClient webClient = new WebClient())
            {
                byte[] response;
                webClient.UseDefaultCredentials = true;
                response = webClient.DownloadData(input.Url + "/_Layouts/VariationLabels.aspx");

                //get viewstate and requestdigest from page
                string viewstate = ExtractHiddenValue("__VIEWSTATE", Encoding.ASCII.GetString(response));
                string requestdigest = ExtractHiddenValue("__REQUESTDIGEST", Encoding.ASCII.GetString(response));

                //format the postdata
                string postData =
                    String.Format("__VIEWSTATE={0}&__REQUESTDIGEST={1}&__EVENTTARGET={2}&__EVENTARGUMENT={3}",
                                  viewstate, requestdigest,
                                  "ctl00$PlaceHolderMain$ctl00$RptControls$variationLabelsCreateHierarchiesToolBarButton",
                                  "");

                //send postdata to server
                webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                webClient.UploadData(input.Url + "/_Layouts/VariationLabels.aspx", "POST",
                                     Encoding.ASCII.GetBytes(postData));
            }
        }

        /// <summary>
        /// This function is used to get the value of a hidden field 
        /// </summary>
        /// <param name="namedelimiter">The name of the hidden field</param>
        /// <param name="html">html of the page to retrieve the value from</param>
        /// <returns>the value of the hidden field</returns>
        private static string ExtractHiddenValue(string namedelimiter, string html)
        {
            string valueDelimiter = "value=\"";

            int viewStateNamePosition = html.IndexOf(namedelimiter);
            int viewStateValuePosition = html.IndexOf(
                valueDelimiter, viewStateNamePosition
                );

            int viewStateStartPosition = viewStateValuePosition +
                                         valueDelimiter.Length;
            int viewStateEndPosition = html.IndexOf("\"", viewStateStartPosition);

            return HttpUtility.UrlEncodeUnicode(
                html.Substring(
                    viewStateStartPosition,
                    viewStateEndPosition - viewStateStartPosition
                    )
                );
        }
    }
}